package android07.newtop.presenter;

import android.content.Intent;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.util.Log;
import android.widget.Toast;

import com.jude.beam.expansion.list.BeamListFragmentPresenter;
import com.jude.easyrecyclerview.adapter.RecyclerArrayAdapter;
import com.lidroid.xutils.DbUtils;
import com.lidroid.xutils.db.sqlite.Selector;
import com.lidroid.xutils.exception.DbException;



import java.util.ArrayList;
import java.util.List;

import android07.newtop.activity.BaseWebActivity;
import android07.newtop.app.APP;
import android07.newtop.fragment.MainFragment;
import android07.newtop.model.MainBeanModel;
import android07.newtop.model.bean.MainBean;
import android07.newtop.model.bean.NewsBean;
import android07.newtop.model.bean.NewsRec;
import android07.newtop.utils.LogUtil;
import android07.newtop.utils.MyUtil;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;


/**
 * 主页
 * Created by hy on 2016/7/7.
 */
public class MainFragmentPresenter extends BeamListFragmentPresenter<MainFragment, NewsBean.ResultBean.DataBean> implements RecyclerArrayAdapter.OnItemClickListener {


    private static final String TAG = MainFragmentPresenter.class.getSimpleName();
    private int page = 1;

    public String tabvalue;

    private ArrayList<NewsBean.ResultBean.DataBean> newstop;

    @Override
    protected void onCreateView(MainFragment view) {
        super.onCreateView(view);
        tabvalue = view.getArguments().getString("tabvalue");
        view.getListView().setLayoutManager(new StaggeredGridLayoutManager(1, StaggeredGridLayoutManager.VERTICAL));
        newstop = new ArrayList<NewsBean.ResultBean.DataBean>();
        onRefresh();
    }

    /**
     * 刷新数据
     */
    @Override
    public void onRefresh() {
        super.onRefresh();
        page = 1;

        new MainBeanModel().getNewsBeanList(tabvalue, new Callback<NewsBean>() {
            @Override
            public void onResponse(Call<NewsBean> call, Response<NewsBean> response) {
                try {
//                MainBean mainBean = new MainBean();
//                mainBean.setNewsBean(body);
                Log.d(TAG, "onResponse: ");

                if(response!=null&&response.body()!=null&&response.body().getResult()!=null){



                List<NewsBean.ResultBean.DataBean> data = response.body().getResult().getData();
                for (NewsBean.ResultBean.DataBean dataBean : data) {

                        NewsBean.ResultBean.DataBean name = DbUtils.create(APP.getInstance()).findFirst(Selector.from(NewsBean.ResultBean.DataBean.class).where("uniquekey", "==", dataBean.getUniquekey()));
                   if(name!=null){
                       dataBean.setIsreaded(true);
                       LogUtil.d(TAG,"當前的行為已經度過");
                   }

                }


                    newstop.clear();
                    newstop.addAll(data);
                    getRefreshSubscriber().onNext(newstop);
                    page++;
                    getAdapter().setOnItemClickListener(MainFragmentPresenter.this);


                }


//                Toast.makeText(getView().getContext(), body.getReason(), Toast.LENGTH_SHORT).show();
                } catch (Exception e) {
                    e.printStackTrace();
                    LogUtil.d(TAG,"数据加载异常="+e.toString());
                }
            }

            @Override
            public void onFailure(Call<NewsBean> call, Throwable t) {
                getRefreshSubscriber().onError(t);
            }
        });


    }

    /**
     * 加载更多 这里由MainFragment 中的getConfig配置决定
     */
    @Override
    public void onLoadMore() {
        super.onLoadMore();


    }

    /**
     * 条目的点击事件
     *
     * @param position
     */

    @Override
    public void onItemClick(int position) {
//        Parent test = db.selector(Parent.class).where("id", "in", new int[]{1, 3, 6}).findFirst();
//        long count = db.selector(Parent.class).where("name", "LIKE", "w%").and("age", ">", 32).count();
//        List<Parent> testList = db.selector(Parent.class).where("id", "between", new String[]{"1", "5"}).findAll();
        if(MyUtil.isFastClick())
            return;

        Intent intenturl = new Intent();
        intenturl.putExtra(BaseWebActivity.BUNDLE_KEY_SHOW_BOTTOM_BAR, false);
        intenturl.putExtra(BaseWebActivity.BUNDLE_KEY_TITLE, newstop.get(position).getTitle());
        intenturl.putExtra(BaseWebActivity.BUNDLE_KEY_URL, newstop.get(position).getUrl());
        intenturl.setClass(getView().getContext(), BaseWebActivity.class);
        NewsBean.ResultBean.DataBean newsbean = newstop.get(position);


        try {
            newsbean.setIsreaded(true);
            DbUtils dbUtils = DbUtils.create(APP.getInstance());
            dbUtils.saveOrUpdate(newsbean);
//            List<NewsBean.ResultBean.DataBean> newsRecs = dbUtils.findAll(NewsBean.ResultBean.DataBean.class);
//
////                    .selector(NewsRec.class).where("uniquekey","=",newstop.get(position).getUniquekey())
////                    .findFirst();
////            assert test!=null;
//            LogUtil.d(TAG,"保持对象ok="+newsRecs.size());


        } catch (DbException e) {
            e.printStackTrace();
            LogUtil.d(TAG,"保持对象出错"+e.toString());
        }
        getView().getContext().startActivity(intenturl);


    }
}
